// routes/captcha.js
import Router from '@koa/router';
import { sendEmailCode } from '../controllers/captcha.js';
import { generateCaptcha, verifyCaptcha, temporaryToken } from '../utils/imageCaptcha2.js'
import redis from '../utils/redis.js';
import { createClient } from 'redis'
let redisN = createClient()
async function checkRateLimit(ip) {
  const key = `rate_limit:${ip}`;
  const exists = await redis.exists(key);
  if (!exists) {
    await redis.set(key, 0, 60); // 初始化值为 0，并设置过期时间
  }

  const currentCount = await redis.incr(key);
  return currentCount <= 6; // 允许每分钟最多 10 次请求
}


const router = new Router({
  prefix: '/api',
  strict: true // 严格路径匹配
});

// 在控制器中调用 
router.get('/captcha/email', async (ctx) => {
  try {
    await sendEmailCode(ctx);
    ctx.body = { code: 200, message: '验证码已发送' };
  } catch (err) {
    ctx.body = { code: 403, message: err.message };
  }
});

// 图形验证码
router.get('/captcha/generate', async (ctx) => {
  const temToken = ctx.request.query.temToken;
  console.log('%c [ temToken ]-38', 'font-size:13px; background:pink; color:#bf2c9f;', temToken)
  if (!temToken) {
    ctx.body = { code: 428, success: false, message: '获取临时token失败' }
    return
  }
  if (!await checkRateLimit(temToken)) {
    ctx.status = 200; // Too Many Requests
    ctx.body = { code: 429, success: false, message: '请求过于频繁' };
    return;
  }
  const captcha = await generateCaptcha(ctx, temToken);

  ctx.body = { code: 200, data: captcha };
});

// 验证结果
router.post('/captcha/verifyCaptcha', async (ctx) => {
  const result = await verifyCaptcha(ctx);
  // 存储验证数据（Redis示例）
  ctx.body = result
  return
});

router.get('/captcha/temporaryToken', async (ctx) => {
  try {
    let { query } = ctx;
    const token = await temporaryToken(ctx);
    console.log('%c [ token ]-67', 'font-size:13px; background:pink; color:#bf2c9f;', token)
    ctx.body = { code: 200, data: token };

  } catch (error) {
    ctx.body = { code: 500, data: '生成指纹失败' };
    throw new Error("生成token失败", error);
  }
});

export default router; 